package com.securities.stock.crawler;

import com.securities.stock.enums.StationEnum;
import com.securities.stock.pojo.Stock;
import com.securities.stock.utils.SSLHttpClientUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CrawlerService {


    private static final Logger LOGGER = LoggerFactory.getLogger(CrawlerService.class);
    private static final String SH_GUPIAO_URL = "https://www.banban.cn/gupiao/list_sh.html";
    private static final String SZ_GUPIAO_URL = "https://www.banban.cn/gupiao/list_sz.html";
    private static final String CYB_GUPIAO_URL = "https://www.banban.cn/gupiao/list_cyb.html";

    /****
     * 上海股票的基本信息
     * @return
     * @throws Exception
     */
    public  List<Stock> crawlerSh() throws Exception{
        String html = SSLHttpClientUtil.get(SH_GUPIAO_URL);
        LOGGER.info("执行url={}, 返回结果={}",SH_GUPIAO_URL,html.length());
        return analysisStock(html, StationEnum.SH);
    }

    /****
     * 深圳的股票基本信息
     * @return
     * @throws Exception
     */
    public  List<Stock> crawlerSz() throws Exception{
        String html = SSLHttpClientUtil.get(SZ_GUPIAO_URL);
        LOGGER.info("执行url={}, 返回结果={}",SZ_GUPIAO_URL,html.length());
        return analysisStock(html,StationEnum.SZ);
    }
    public  List<Stock> crawlerCyb() throws Exception{
        String html = SSLHttpClientUtil.get(CYB_GUPIAO_URL);
        LOGGER.info("执行url={}, 返回结果={}",CYB_GUPIAO_URL,html.length());
        return analysisStock(html,StationEnum.CYB);
    }


    private List<Stock> analysisStock(String html,StationEnum station) throws Exception {
        Document document = Jsoup.parse(html);// 解析列表页面
        Elements lis = document.select("#ctrlfscont li");
        List<Stock> stocks=new ArrayList<>();
        for (Element li : lis) {
            String s=li.text();
            String str = new String(s.getBytes("ISO8859-1"),"UTF-8");
            int separateIndex=str.length()-8;
            String name=str.substring(0,separateIndex);
            String code=str.substring(separateIndex+1,str.length()-1);
            Stock stock=new Stock();
            stock.setStation(station.getCode());
            stock.setPlate(station.getName());
            stock.setCode(code);
            stock.setName(name);
            stock.setType(1);
            stocks.add(stock);
        }
        return  stocks;
    }

    public static void main(String[] args) throws Exception{
        CrawlerService crawlerService=new CrawlerService();
        crawlerService.crawlerSh();
    }

    /****
     * 抓取流通股本和总股本
     * @param stock
     * @throws Exception
     */
    public Stock crawlerEquity(Stock stock) throws Exception{
        String url="http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_StockStructure/stockid/"+stock.getCode()+".phtml";
        String html = SSLHttpClientUtil.get(url);
        LOGGER.info("执行url={}, 返回结果={}",url,html.length());
        Document document = Jsoup.parse(html);// 解析列表页面
        Elements ltsz = document.select("#StockStructureNewTable0 tr");
        Stock gbStock=new Stock();
        gbStock.setId(stock.getId());
        for(int i=0;i<ltsz.size();i++){
            Element tr = ltsz.get(i);
            if(i==0) {
                Elements tds = tr.children();
                String s=tds.get(0).text();
                //String str = new String(s.getBytes("ISO8859-1"),"GBK");
                String str = s;
                String gpName= str.split("-")[0];
                int separateIndex=gpName.length()-9;
                String name=str.substring(0,separateIndex);
                gbStock.setName(name);
                LOGGER.info("名称：{}",name);
            }
            if(i==5) {
                Elements tds = tr.children();
                String zgbName=tds.get(0).text();
                //String zgbNameStr = new String(zgbName.getBytes("ISO8859-1"),"GBK");
                String zgbNameStr =zgbName;
                String zgbCount=tds.get(1).text();
                //String zgbCountStr = new String(zgbCount.getBytes("ISO8859-1"),"GBK");
                String zgbCountStr=zgbCount;
                int indexOf= zgbCountStr.indexOf("万股");
                String zgbNum=  zgbCountStr.substring(0,indexOf);
                BigDecimal zgbDecimal=  new BigDecimal(zgbNum.trim()).multiply(new BigDecimal(10000));
                LOGGER.info("{}:\t{}",zgbNameStr,zgbDecimal);
                gbStock.setEquityTotal(zgbDecimal);
            }
            if(i==7) {
                Elements tds = tr.children();
                String ltgName=tds.get(0).text();
                //String ltgNameStr = new String(ltgName.getBytes("ISO8859-1"),"GBK");
                String ltgNameStr = ltgName;
                String ltgCount=tds.get(1).text();
                //String ltgCountStr = new String(ltgCount.getBytes("ISO8859-1"),"GBK");
                String ltgCountStr =ltgCount;
                int indexOf= ltgCountStr.indexOf("万股");
                String ltgNum=  ltgCountStr.substring(0,indexOf);
                BigDecimal ltgDecimal=  new BigDecimal(ltgNum.trim()).multiply(new BigDecimal(10000));
                LOGGER.info("{}:\t{}",ltgNameStr,ltgDecimal);
                gbStock.setEquityCirculate(ltgDecimal);
            }
        }
        return  gbStock;
    }

    public void crawlerBase() throws Exception{
        String url="http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_StockStructureHistory/stockid/600171/stocktype/LiuTongA.phtml";
        String html = SSLHttpClientUtil.get(url);
        LOGGER.info("执行url={}, 返回结果={}",url,html.length());
        Document document = Jsoup.parse(html);// 解析列表页面
        Elements ltsz = document.select("#toolbar div");
        for (Element tr : ltsz) {
            String s=tr.text();
            //String str = new String(s.getBytes("ISO8859-1"),"GBK");
            String str =s;
            LOGGER.info("ltsz：{}",str);
        }

    }
}
